package com.sicau.tools;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

public class TerminalOperationTool {

    /**
     * 执行终端命令
     * @param command 要执行的终端命令
     * @return 命令执行结果字符串
     */
    @Tool(description = "执行终端命令")
    public String executeTerminalCommand(@ToolParam(description = "要执行的终端命令") String command) {
        try {
            // 使用 ProcessBuilder 替代 deprecated 的 Runtime.exec
            ProcessBuilder processBuilder = new ProcessBuilder();
            
            // 根据操作系统设置命令
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                processBuilder.command("cmd.exe", "/c", command);
            } else {
                processBuilder.command("sh", "-c", command);
            }
            
            Process process = processBuilder.start();
            process.waitFor();
            
            // 获取命令执行的输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String output = reader.lines().collect(Collectors.joining("\n"));
                return output.isEmpty() ? "命令执行成功" : output;
            }
        } catch (Exception e) {
            return "命令执行失败: " + e.getMessage();
        }
    }

}
